package com.mj.Set;

import com.mj.Set.list.LinkedList;
import com.mj.Set.list.List;

/**
 * @Author: LDeng
 * @Date: 2021-03-10 8:50
 */
public class ListSet<E> implements Set<E> {

    private List<E> list=new LinkedList<>();


    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public boolean contains(E element) {
        return list.contains(element);
    }

    @Override
    public void add(E element) {
        int index = list.indexOf(element);
        if(index!=List.ELEMENT_NOT_FOUND){
            list.set(index,element);//元素存在=>覆盖
        }else{
            list.add(element);//元素不存在=> 添加
        }
    }

    @Override
    public void remove(E element) {
        int index = list.indexOf(element);
        if(index!=List.ELEMENT_NOT_FOUND){
            list.remove(index);
        }
    }

    @Override
    public void traversal(Visitor visitor) {
        if(visitor==null) return;
        int size= list.size();
        for (int i = 0; i < size; i++) {
            if(visitor.visit(list.get(i))) return;//找到了就返回
        }
    }
}
